<template>
  <navigation></navigation>
  <div class="bg-gradient-to-br from-gray-50 to-blue-50/30 min-h-screen py-12">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 头部导航 -->
      <div class="flex items-center justify-between mb-8">
        <h1 class="text-2xl font-bold text-gray-800">个人信息管理</h1>
        <button 
          @click="toPersonalCenter"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          返回个人中心
        </button>
      </div>

      <!-- 主内容区 -->
      <div class="bg-white rounded-xl shadow-lg p-8">
        <div class="flex flex-col lg:flex-row gap-8">
          <!-- 头像上传区 -->
          <div class="flex flex-col items-center w-full lg:w-1/3">
            <div 
              class="relative w-48 h-48 rounded-full cursor-pointer group"
              @click="triggerFileUpload"
            >
              <img 
                :src="avatarPreview || form.userImg"
                class="w-full h-full object-cover rounded-full border-4 border-white shadow-lg transition-all duration-300 group-hover:scale-105"
                alt="用户头像"
              />
              <div class="absolute inset-0 bg-black/50 flex flex-col items-center justify-center rounded-full opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                <svg class="w-8 h-8 text-white mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
                <span class="text-white text-sm">点击修改头像</span>
              </div>
              <input 
                type="file"
                ref="fileInput"
                accept="image/*"
                class="hidden"
                @change="handleFileUpload"
              />
            </div>
            
            <button 
              @click="uploadAvatar"
              :disabled="uploading"
              class="mt-4 px-6 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors disabled:opacity-50"
            >
              {{ uploading ? '上传中...' : '保存头像' }}
            </button>
          </div>

          <!-- 表单区 -->
          <form class="flex-1 space-y-6" @submit.prevent="submitForm">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <!-- 姓名 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">姓名</label>
                <div class="relative">
                  <img src="/src/assets/img/姓名.png" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.name"
                    type="text"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入您的姓名"
                  >
                </div>
              </div>

              <!-- 年龄 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">年龄</label>
                <div class="relative">
                  <img src="/src/assets/img/年龄.png" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.age"
                    type="number"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入您的年龄"
                  >
                </div>
              </div>

              <!-- 学院 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">学校</label>
                <div class="relative">
                  <img src="/src/assets/img/学校.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <select 
                    v-model="form.college"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none"
                  >
                    <option value="">请选择学校</option>
                    <option>贵州大学</option>
                    <option>贵州师范大学</option>
                    <option>贵州医科大学</option>
                    <option>遵义医科大学</option>
                    <option>贵州财经大学</option>
                    <option>其他</option>
                  </select>
                </div>
              </div>

              <!-- 学历 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">学历</label>
                <div class="relative">
                  <img src="/src/assets/img/学历.png" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <select
                    v-model="form.education"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none"
                  >
                    <option value="">请选择学历</option>
                    <option>专科</option>
                    <option>本科</option>
                    <option>硕士</option>
                    <option>博士</option>
                    <option>其他</option>
                  </select>
                </div>
              </div>

              <!-- 邮箱 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">邮箱</label>
                <div class="relative">
                  <img src="/src/assets/img/邮箱.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.email"
                    type="email"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入您的邮箱"
                  >
                </div>
              </div>
              <!-- 电话 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">手机号</label>
                <div class="relative">
                  <img src="/src/assets/img/电话.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.phone"
                    type="phone"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入您的手机号"
                  >
                </div>
              </div>
              <!-- 加入时间 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">加入时间</label>
                <div class="relative">
                  <img src="/src/assets/img/日期.png" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <input
                    v-model="form.joinDate"
                    type="date"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                </div>
              </div>

              <!-- 意向岗位 -->
              <div class="space-y-2">
                <label class="block text-gray-700 font-medium">意向岗位</label>
                <div class="relative">
                  <img src="/src/assets/img/岗位管理.svg" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5">
                  <select 
                    v-model="form.position"
                    class="w-full pl-10 pr-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none"
                  >
                    <option value="">请选择岗位</option>
                    <option>前端开发工程师</option>
                    <option>Java后端开发</option>
                    <option>UI/UX设计师</option>
                    <option>人工智能算法工程师</option>
                    <option>运维测试工程师</option>
                    <option>数据工程师</option>
                    <option>其他</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex gap-4 pt-8">
              <button
                type="button"
                @click="resetForm"
                class="flex-1 px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
              >
                重置信息
              </button>
              <button
                type="submit"
                class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                保存修改
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 获取路由实例
const router = useRouter()

// 默认头像
const defaultAvatar = '/src/assets/default-avatar.png'

// 表单数据
const form = reactive({
  name: '罗峰',
  age: 24,
  school: '计算机科学与技术学院',
  education: '本科',
  email: 'luofeng@university.com',
  position: '前端开发工程师',
  joinDate: '2023-09-01', 
  phone:'18386323743',
  userImg: defaultAvatar
})

// 头像上传相关
const fileInput = ref(null)
const avatarPreview = ref('')
const selectedFile = ref(null)
const uploading = ref(false)

// 从本地存储加载用户数据
const loadUserData = () => {
  try {
    const savedData = localStorage.getItem('userData')
    if (savedData) {
      const parsedData = JSON.parse(savedData)
      Object.assign(form, parsedData)
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 页面加载时初始化
onMounted(() => {
  loadUserData()
})

// 触发文件选择
const triggerFileUpload = () => {
  fileInput.value.click()
}

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 文件验证
  if (!file.type.startsWith('image/')) {
    ElMessage.error('仅支持图片格式（JPEG/PNG）')
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
  selectedFile.value = file
}

// 上传头像
const uploadAvatar = () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要上传的头像')
    return
  }

  try {
    uploading.value = true
    
    // 使用本地存储模拟头像上传
    const reader = new FileReader()
    reader.onload = (e) => {
      form.userImg = e.target.result
      saveUserData()
      ElMessage.success('头像更新成功')
    }
    reader.onerror = () => {
      ElMessage.error('头像上传失败')
    }
    reader.onloadend = () => {
      uploading.value = false
      selectedFile.value = null
    }
    reader.readAsDataURL(selectedFile.value)
  } catch (error) {
    ElMessage.error('头像上传失败')
    console.error('上传错误:', error)
    uploading.value = false
  }
}

// 保存用户数据到本地存储
const saveUserData = () => {
  try {
    const userData = {
      ...form,
      // 确保只保存必要的数据
      userImg: form.userImg
    }
    localStorage.setItem('userData', JSON.stringify(userData))
    // 使用localStorage事件通知其他页面
    localStorage.setItem('userInfoUpdateTrigger', Date.now().toString())
  } catch (error) {
    console.error('保存用户数据失败:', error)
  }
}

// 提交表单
const submitForm = () => {
  try {
    saveUserData()
    ElMessage.success('个人信息已更新')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存错误:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '罗峰',
    age: 24,
    school: '计算机科学与技术学院',
    education: '本科',
    email: 'luofeng@university.com',
    position: '前端开发工程师',
    joinDate: '2023-09-01', // 重置时恢复默认加入时间
    phone:'18386323743',
    userImg: defaultAvatar
  })
  avatarPreview.value = ''
  ElMessage.info('已重置所有信息')
}

// 跳转到个人中心页面
const toPersonalCenter = () => {
  router.push('/personalcenter')
}
</script>

<style scoped>
/* 自定义加载动画 */
@keyframes spin {
  to { transform: rotate(360deg); }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* 下拉箭头样式 */
select {
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 1rem center;
  background-size: 1em;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
  
  .flex-col.lg\:flex-row {
    flex-direction: column;
  }
  
  .w-full.lg\:w-1\/3 {
    width: 100%;
    margin-bottom: 2rem;
  }
}

/* 头像悬停效果 */
.group:hover .group-hover\:scale-105 {
  transform: scale(1.05);
  transition: transform 0.3s ease;
}

/* 按钮过渡效果 */
.transition-colors {
  transition: background-color 0.3s ease;
}
</style>
